<template>
    <div class="page-container">

             <!-- 顶部标题栏 -->
             <header class="header">
                <BackBtn @click="handleBack" />
                <h1>结束的签到</h1>
                <Time />
            </header>

        <!-- 主要内容区域 -->
        <div class="main-content" style="margin-top: 160px;">
            <!-- 搜索和筛选区域 -->
            <div class="search-section">
                <el-input v-model="searchText" placeholder="支持搜索签到项目" class="search-input">
                    <template #append>
                        <el-button type="danger" class="search-btn" @click="handleSearch">
                            <el-icon class="search-icon">
                                <Search />
                            </el-icon>
                        </el-button>
                    </template>
                </el-input>

                <div class="filter-section">
                    <!-- 日期范围选择 -->
                    <div class="date-range-picker">
                        <el-date-picker 
                            v-model="dateRange[0]" 
                            type="date" 
                            placeholder="开始日期" 
                            class="date-picker"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                            @change="handleFilterChange" 
                        />
                        <span class="separator">—</span>
                        <el-date-picker 
                            v-model="dateRange[1]" 
                            type="date" 
                            placeholder="结束日期" 
                            class="date-picker"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                            @change="handleFilterChange" 
                        />
                    </div>

                    <!-- 排序选择 -->
                    <el-select v-model="sortBy" placeholder="排序：发起日期(倒序)" @change="handleFilterChange">
                        <el-option label="发起日期(倒序)" value="desc" />
                        <el-option label="发起日期(正序)" value="asc" />
                        <el-option label="签到日期(倒序)" value="desc1" />
                        <el-option label="签到日期(正序)" value="asc1" />
                    </el-select>

                    <!-- 状态筛选 -->
                    <el-select v-model="status" placeholder="状态筛选：全部" @change="handleFilterChange">
                        <el-option label="状态筛选：全部" value="all" />
                        <el-option label="已签齐" value="signed" />
                        <el-option label="未签齐" value="unsigned" />
                    </el-select>

                    <!-- 导出按钮 -->
                    <el-button type="danger" @click="handleExport" style="width: 180px;background-color: #c62828;border: none;margin-left: 150px;">导出列表</el-button>
                </div>
            </div>

            <!-- 表格区域 -->
            <div class="table-section"  v-loading="loading" element-loading-text="加载中..." element-loading-background="rgba(0,0,0,0)">
                <div class="sign-list">
                    <!-- 表头 -->
                    <div class="sign-header">
                        <div class="header-item title">签到项目</div>
                        <div class="header-item status">签到状态</div>
                        <div class="header-item sign-date">签到时间</div>
                        <div class="header-item create-date">发起日期</div>
                        <div class="header-item actions"></div>
                    </div>

                    <!-- 数据列表 -->
                    <div v-for="(item, index) in signs" :key="index" class="sign-item">
                        <div class="red-line"></div>
                        <div class="sign-info">
                            <div class="info-title">{{ item.title }}</div>
                            <div class="info-status">
                                {{ item.signStatus }}
                                <el-button class="showOverMeeting" @click="handleDetail(item)">
                                    签到情况
                                </el-button>
                            </div>
                            <div class="info-sign-date">{{ item.startTime }}至{{ item.endTime }}</div>
                            <div class="info-create-date">{{ item.createdAt }}</div>
                            <div class="info-actions">
                                <el-button type="primary" @click="handleDataDetail(item)">详情</el-button>
                            </div>
                        </div>
                    </div>
                </div>

         <!-- 分页 -->
         <div class="pagination-section">
                        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize"
                            :page-sizes="[3, 5, 10, 15]" :background="false" layout="prev, pager, next, jumper"
                            :total="total" @size-change="onSizeChange" @current-change="onCurrentChange" />
                    </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted ,onUnmounted} from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useSignsStore } from '@/stores/signs'
import { storeToRefs } from 'pinia'
import { exportSigns } from '@/api/sign'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'
const router = useRouter()
const signsStore = useSignsStore()
const {
    signs,
    total,
    pageNum,
    pageSize,
    dateRange,
    sortBy,
    loading,
    searchText,
    status
} = storeToRefs(signsStore)


// 获取已结束签到列表数据
const fetchEndedSignList = () => {
    signsStore.fetchEndedSigns()
}

// 处理搜索
const handleSearch = () => {
    pageNum.value = 1
    fetchEndedSignList()
}

// 处理筛选条件变化
const handleFilterChange = () => {
    pageNum.value = 1
    fetchEndedSignList()
}

// 分页大小改变
const onSizeChange = (val) => {
    pageSize.value = val
    fetchEndedSignList()
}

// 页码改变
const onCurrentChange = (val) => {
    pageNum.value = val
    fetchEndedSignList()
}

// 查看签到情况
const handleDetail = (row) => {
    router.push(`/sign/detail/${row.mid}`)
}

// 查看签到详情
const handleDataDetail = (row) => {
    router.push({
        path: `/sign/data/${row.mid}`,
        query: { from: 'ended' }  // 添加来源标识
    })
}


// 导出列表
const handleExport = async () => {
    try {
        console.log('导出参数:', {
            sortBy: sortBy.value,
            startDate: dateRange.value[0],
            endDate: dateRange.value[1],
            searchText: searchText.value,
            status: status.value,
        })
        
        const response = await exportSigns({
            sortType: sortBy.value,
            startDate: dateRange.value[0],
            endDate: dateRange.value[1],
            searchText: searchText.value,
            status: status.value === 'all' ? '' : status.value,
        })

        // 调试信息
        console.log('Response headers:', response.headers)
        console.log('Response type:', response.type)
        console.log('Response size:', response.size)

        // 检查响应是否为空
        if (!response || response.size === 0) {
            throw new Error('导出的文件为空')
        }

        // 检查响应类型
        const contentType = response.type
        if (!contentType.includes('spreadsheetml.sheet')) {
            const text = await response.text()
            throw new Error(text || '导出的文件格式不正确')
        }

        // 创建下载链接
        const blob = new Blob([response], { type: contentType })
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl
        link.download = `签到列表_${new Date().toLocaleDateString()}.xlsx`
        document.body.appendChild(link)
        link.click()
        
        // 清理资源
        window.URL.revokeObjectURL(downloadUrl)
        document.body.removeChild(link)
    
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('Export error:', error)
        ElMessage.error(error.message || '导出失败')
    }
}

const handleBack = () => {
    router.back();
    signsStore.fetchSigns()
}


// 重置所有筛选条件的函数
const resetFilters = () => {
    searchText.value = ''  // 重置搜索文本
    dateRange.value = [null, null]  // 重置日期范围
    status.value = 'all'  // 重置状态筛选
    sortBy.value = 'desc'  // 重置时间排序为默认的倒序
    pageNum.value = 1  // 重置页码
}


onMounted(() => {
    resetFilters()  // 初始化重置
    fetchEndedSignList()
})

// 添加组件卸载钩子
onUnmounted(() => {
  pageNum.value = 1  // 组件卸载时重置页码
})

</script>

<style scoped>
@import '@/assets/css/meeting/list.css';
@import '@/assets/css/header/index.css';
@import '@/assets/css/others/pagination.css';
@import '@/assets/css/others/btn.css';
@import '@/assets/css/others/dateEditor.css';
@import '@/assets/css/others/select.css';

/* 签到列表样式 */
.sign-list {
  border-radius: 4px;
  margin-bottom: 20px;
  margin-left: 125px;
  min-width: 1000px;
  width: 80%;
}

.sign-header {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr 1fr;
  padding: 15px;
  /* background-color: #f5f7fa; */
  color: black;
}

.sign-item {
  background: #fff;
  border-radius: 10px;
  position: relative;
  border: 1px solid #e4e7ed;
  margin-bottom: 10px;
  transition: all 0.3s ease;
}

.sign-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-color: #c62828;
}


.red-line {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  height: 35px;
  background: #c62828;
  border-radius: 8px;
  margin: 13px;
  transition: height 0.3s ease;
}

.sign-item:hover .red-line {
  height: 60%;
}


.sign-info {
    display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr 1fr;
  padding: 10px;
  align-items: center;
}

.info-title {
    margin-left: 12px;
}

.info-status {
    display: flex;
    align-items: center;
    gap: 10px;
}

.info-actions {
    display: flex;
    gap: 10px;
}

.showOverMeeting {
    margin-right: 10px;
}

.search-section {
    /* background: white; */
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 10px;
    /* box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1); */
    margin-left: 105px;
    min-width: 1000px;
    width: 84%;
  }
  
  /* 搜索框特定样式 */
  .search-input {
    margin-bottom: 20px;
  }
  
  .search-input :deep(.el-input__wrapper) {
    height: 40px !important;
    border-radius: 8px 0 0 8px !important;
    padding: 0 12px !important;
    box-sizing: border-box;
  }
  
  .search-input :deep(.el-input:hover .el-input__wrapper) {
    box-shadow: 0 0 0 1px #c62828 inset !important;
  }
  
  .search-input :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #c62828 inset !important;
  }
  
  .search-input :deep(.el-input-group__append) {
    padding: 0 !important;
    border: none !important;
    background: none !important;
  }
  
  /* 搜索按钮样式 */
  .search-btn {
    background-color: #c62828 !important;
    border: none;
    height: 40px;
    width: 180px;
    color: white;
    padding: 5px 10px;
    border-radius: 0 8px 8px 0 !important;
    cursor: pointer;
  }
  
  .search-btn:hover {
    background-color: #a91919 !important;
  }
  
  .search-btn .el-icon {
    font-size: 20px;
    color: white;
  }
</style>